<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改订单状态"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="status-form"
    >
      <el-form-item label="当前状态">
        <el-tag :type="getStatusType(currentStatus)">
          {{ getStatusText(currentStatus) }}
        </el-tag>
      </el-form-item>

      <el-form-item label="更改为" prop="status">
        <el-select
          v-model="formData.status"
          placeholder="请选择新状态"
          style="width: 100%"
          @change="handleStatusChange"
        >
          <el-option
            v-for="option in statusOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
            :disabled="option.disabled"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="needReturnReason"
        label="退货原因"
        prop="returnReason"
      >
        <el-input
          v-model="formData.returnReason"
          type="textarea"
          :rows="3"
          :placeholder="
            isReturnApprovalOrReject
              ? '后端提供的退货原因（不可编辑）'
              : '请输入退货原因（必填）'
          "
          :readonly="isReturnApprovalOrReject"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>

      <!-- 退货商品信息 (仅在退货同意或退货拒绝时显示) -->
      <el-form-item
        v-if="needReturnReason && hasReturnItems"
        label="退货商品"
        class="return-items-section"
      >
        <div class="return-items-container">
          <div
            class="return-item"
            v-for="item in getReturnItems()"
            :key="item.id"
          >
            <div class="item-info">
              <span class="item-name">{{
                item.product?.pName || "未知商品"
              }}</span>
              <span class="item-spec" v-if="item.product?.pSpecifications">
                （{{ item.product.pSpecifications }}）
              </span>
            </div>
            <div class="item-details">
              <span class="item-price">￥{{ item.pPrice }}</span>
              <span class="item-quantity">
                退货数量：{{ item.returnQuantity || item.pNumber }}/{{
                  item.pNumber
                }}
              </span>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item
        v-if="needReturnReason"
        label="管理员备注"
        prop="adminReturnRemark"
      >
        <el-input
          v-model="formData.adminReturnRemark"
          type="textarea"
          :rows="3"
          placeholder="请输入管理员处理备注（必填）"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import orderApi from "@/api/order";
import { safeNumber } from "@/utils/precision";

interface FormData {
  status: string;
  returnReason: string;
  adminReturnRemark: string;
}

interface Props {
  visible: boolean;
  orderId: string;
  currentStatus: string;
  orderData?: any; // 当前订单数据，用于获取已存在的退货原因
}

interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const loading = ref(false);
const dialogVisible = ref(false);

const formData = ref<FormData>({
  status: "",
  returnReason: "",
  adminReturnRemark: "",
});

// 状态选项配置
const statusOptions = computed(() => {
  // 所有可用的状态选项
  const allOptions = [
    { value: "PENDING", label: "待确认", disabled: false },
    { value: "PENDING_SHIP", label: "待发货", disabled: false },
    { value: "SHIPPED", label: "已发货", disabled: false },
    { value: "PENDING_PAYMENT", label: "待付款", disabled: false },
    { value: "COMPLETED", label: "已完成", disabled: false },
    { value: "RETURN_REQUESTED", label: "申请退货", disabled: false },
    { value: "RETURN_APPROVED", label: "退货同意", disabled: false },
    { value: "RETURN_REJECTED", label: "退货拒绝", disabled: false },
    { value: "RETURNED", label: "已退货", disabled: false },
    { value: "CANCELLED", label: "已取消", disabled: false },
  ];

  // 根据当前订单状态限制可选择的状态
  if (props.currentStatus === "RETURN_REQUESTED") {
    // 申请退货状态只能修改为：退货同意或退货拒绝
    return allOptions.filter(
      (option) =>
        option.value === "RETURN_APPROVED" || option.value === "RETURN_REJECTED"
    );
  }

  // 其他状态返回所有选项
  return allOptions;
});

// 是否需要填写退货原因
const needReturnReason = computed(() => {
  return (
    formData.value.status === "RETURN_APPROVED" ||
    formData.value.status === "RETURN_REJECTED"
  );
});

// 是否是退货同意或退货拒绝状态（此时应显示已有的退货原因且不可编辑）
const isReturnApprovalOrReject = computed(() => {
  return (
    (formData.value.status === "RETURN_APPROVED" ||
      formData.value.status === "RETURN_REJECTED") &&
    props.orderData?.returnReason
  );
});

// 是否有退货商品信息
const hasReturnItems = computed(() => {
  return getReturnItems().length > 0;
});

// 获取退货商品列表
const getReturnItems = () => {
  if (!props.orderData || !props.orderData.orderItems) return [];

  // 尝试解析remark中的JSON数据（新格式）
  if (props.orderData.remark && props.orderData.remark.startsWith("[")) {
    try {
      const returnItems = JSON.parse(props.orderData.remark);
      return props.orderData.orderItems
        .map((item: any) => {
          const returnItem = returnItems.find(
            (r: any) => r.orderItemId === item.id
          );
          if (returnItem) {
            return {
              ...item,
              returnQuantity: returnItem.returnQuantity,
            };
          }
          return null;
        })
        .filter(Boolean);
    } catch (error) {
      console.error("解析退货数据失败:", error);
    }
  }

  // 兼容旧格式：如果remark中包含商品ID（用逗号分隔），则表示部分商品退货
  if (props.orderData.remark && props.orderData.remark.includes(",")) {
    const returnItemIds = props.orderData.remark
      .split(",")
      .filter((id: string) => id.trim());
    return props.orderData.orderItems
      .filter((item: any) => returnItemIds.includes(item.id))
      .map((item: any) => ({
        ...item,
        returnQuantity: safeNumber(item.pNumber, 0), // 旧格式默认为全部数量
      }));
  }

  // 否则返回所有商品（全部退货）
  return props.orderData.orderItems.map((item: any) => ({
    ...item,
    returnQuantity: safeNumber(item.pNumber, 0),
  }));
};

// 表单验证规则
const rules = computed(() => ({
  status: [{ required: true, message: "请选择新状态", trigger: "change" }],
  returnReason:
    needReturnReason.value && !isReturnApprovalOrReject.value
      ? [
          { required: true, message: "请输入退货原因", trigger: "blur" },
          { min: 5, message: "退货原因至少5个字符", trigger: "blur" },
        ]
      : [],
  adminReturnRemark: needReturnReason.value
    ? [
        { required: true, message: "请输入管理员备注", trigger: "blur" },
        { min: 5, message: "管理员备注至少5个字符", trigger: "blur" },
      ]
    : [],
}));

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    PENDING: "待确认",
    PENDING_SHIP: "待发货",
    SHIPPED: "已发货",
    PENDING_PAYMENT: "待付款",
    COMPLETED: "已完成",
    RETURN_REQUESTED: "申请退货",
    RETURN_APPROVED: "退货同意",
    RETURN_REJECTED: "退货拒绝",
    RETURNED: "已退货",
    CANCELLED: "已取消",
  };
  return statusMap[status] || "未知状态";
};

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    PENDING: "info",
    PENDING_SHIP: "info",
    SHIPPED: "success",
    PENDING_PAYMENT: "warning",
    COMPLETED: "success",
    RETURN_REQUESTED: "primary",
    RETURN_APPROVED: "danger",
    RETURN_REJECTED: "info",
    RETURNED: "danger",
    CANCELLED: "danger",
  };
  return typeMap[status] || "info";
};

// 监听弹窗显示状态
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
    if (newVal) {
      resetForm();
    }
  }
);

watch(
  () => dialogVisible.value,
  (newVal) => {
    emit("update:visible", newVal);
  }
);

// 状态变化处理
const handleStatusChange = () => {
  // 清空退货相关字段
  if (!needReturnReason.value) {
    formData.value.returnReason = "";
    formData.value.adminReturnRemark = "";
  } else if (isReturnApprovalOrReject.value) {
    // 如果是退货同意或退货拒绝状态，且订单已有退货原因，则使用后端的退货原因
    formData.value.returnReason = props.orderData?.returnReason || "";
  }
  // 清除验证
  formRef.value?.clearValidate();
};

// 重置表单
const resetForm = () => {
  formData.value = {
    status: "",
    returnReason: "",
    adminReturnRemark: "",
  };
  formRef.value?.clearValidate();
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    if (formData.value.status === props.currentStatus) {
      ElMessage.warning("请选择不同的状态");
      return;
    }

    loading.value = true;

    const submitData: any = {
      status: formData.value.status,
    };

    if (needReturnReason.value) {
      // 如果是显示已有退货原因的情况，使用后端的退货原因；否则使用表单输入的退货原因
      submitData.returnReason = isReturnApprovalOrReject.value
        ? props.orderData?.returnReason
        : formData.value.returnReason;
      submitData.adminReturnRemark = formData.value.adminReturnRemark;
    }

    const res: any = await orderApi.updateOrderStatus(
      props.orderId,
      submitData
    );

    if (res.data.ok) {
      ElMessage.success("订单状态修改成功");
      emit("success");
      handleClose();
    } else {
      ElMessage.error(res.message || "修改失败");
    }
  } catch (error) {
    ElMessage.error("修改失败，请重试");
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.status-form {
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-textarea__inner) {
  resize: none;
}

/* 退货商品样式 */
.return-items-section {
  margin-bottom: 20px;
}

.return-items-container {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  background-color: #fafafa;
  max-height: 300px;
  overflow-y: auto;
}

.return-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background-color: #ffffff;
  border-radius: 6px;
  border-left: 3px solid #ff6b35;
  margin-bottom: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.return-item:last-child {
  margin-bottom: 0;
}

.item-info {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-name {
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.item-spec {
  font-size: 12px;
  color: #666;
  background-color: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
}

.item-details {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-shrink: 0;
}

.item-price {
  font-weight: 600;
  color: #ff6b35;
  font-size: 14px;
}

.item-quantity {
  color: #666;
  font-size: 13px;
  white-space: nowrap;
}
</style>
